'use strict';

module.exports = app => {
   class Service extends app.Service {
      //登录接口
      async login(msg) {
         const { ctx, app } = this;
         try {
            let user = await app.mysql.query('SELECT * FROM `user` where id= ?', [Number(msg.userId)])
            let uPassword = ctx.helper.decrypt(user[0].password, 'egg')
            let mPassword = ctx.helper.decrypt(msg.password, 'egg')
            if (user[0].name != msg.name) {
               return ctx.helper.processInformation(false, [], '用户名不正确', 200, 401)
            }
            if (uPassword != mPassword) {
               return ctx.helper.processInformation(false, [], '密码不正确', 200, 401)
            }
            if (uPassword == mPassword && user[0].name == msg.name) {
               return ctx.helper.processInformation(true, user, '成功', 200, 200, true)
            }
         } catch (error) {
            return ctx.helper.processInformation(false, [], '服务器错误', 200, 500)
         }
      }
      // 所有用户
      async userList(param, behavior) {
         const { ctx, app } = this;
         console.log('\x1B[36m%s\x1B[0m', param, behavior)
         try {
            switch (behavior) {
               case 'add':
                  let userName = await app.mysql.query('SELECT name FROM `user`  where name=?', [param.name])
                  if (userName.length) {
                     return ctx.helper.processInformation(false, [], '用户名重复', 200, 200)
                  }
                  await app.mysql.query('INSERT into `user` set name = ?,PASSWORD =?', [param.name, ctx.helper.encrypt(param.password, 'egg')])
                  return ctx.helper.processInformation(true, [], '添加成功', 200, 200)
                  break;
               case 'del':
                  if (param.name == 'admin') {
                     return ctx.helper.processInformation(false, [], '管理员不可删除', 200, 200)
                  }
                  await app.mysql.query('DELETE  FROM user WHERE id =?', param.id)
                  return ctx.helper.processInformation(true, [], '删除成功', 200, 200)
                  break;
               case 'updata':
                  const result = await this.app.mysql.update('user', param)
                  return ctx.helper.processInformation(true, [], '修改成功', 200, 200)
                  break;

               case 'select':
                  let user = await app.mysql.query('SELECT id,name,age,phone,userId FROM `user`')
                  return ctx.helper.processInformation(true, user, '成功', 200, 200)
                  break;
            }
         } catch (error) {
            console.log('\x1B[36m%s\x1B[0m', error)
            return ctx.helper.processInformation(false, [], '服务器错误', 200, 500)
         }
      }
   }
   return Service;
};
